package colite

import (
	"bytes"
	"io/ioutil"
	"net/http"
	"strings"

	"golang.org/x/net/html/charset"
)

// Response 响应类
type Response struct {
	// StatusCode 响应状态码
	StatusCode int

	// Headers 响应头
	Headers *http.Header

	// Body 响应主体
	Body []byte

	// Request 当前请求实例
	Request *Request

	// Ctx 上下文环境
	Ctx *Context
}

// fixCharset 修改响应主体字符编码
func (r *Response) fixCharset(defaultEncoding string) error {
	// 无数据直接返回
	if len(r.Body) == 0 {
		return nil
	}

	// 如果已指定字符编码则直接进行转换
	if defaultEncoding != "" {
		tmpBody, err := encodeBytes(r.Body, "text/plain; charset="+defaultEncoding)
		if err != nil {
			return err
		}
		r.Body = tmpBody
		return nil
	}

	// utf8编码或图片视频音频字体类自动返回
	contentType := strings.ToLower(r.Headers.Get("Content-Type"))
	if !strings.Contains(contentType, "charset") ||
		strings.Contains(contentType, "utf-8") ||
		strings.Contains(contentType, "utf8") ||
		strings.Contains(contentType, "image/") ||
		strings.Contains(contentType, "video/") ||
		strings.Contains(contentType, "audio/") ||
		strings.Contains(contentType, "font/") {
		return nil
	}

	// 转换字符编码
	tmpBody, err := encodeBytes(r.Body, contentType)
	if err != nil {
		return err
	}
	r.Body = tmpBody
	return nil
}

// encodeBytes 转换字符编码
func encodeBytes(b []byte, contentType string) ([]byte, error) {
	r, err := charset.NewReader(bytes.NewReader(b), contentType)
	if err != nil {
		return nil, err
	}
	return ioutil.ReadAll(r)
}
